﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using Common.Utilities;
using Common.Utilities.Dispatcher;
using Common.Utilities.NetworkUtilities;

namespace Workflows.Components.Triggers
{
    /// <summary>
    /// 
    /// </summary>
    public partial class HotFolderEditor : Form, IComponentEditor 
    {
        private object _OwnerActivityNode;
        private HotFolderTrigger _HotFolderTrigger;

        /// <summary>
        /// 
        /// </summary>
        public HotFolderEditor()
        {
            InitializeComponent();
        }

        private void HotFolderEditor_Load(object sender, EventArgs e)
        {

        }

        public event UpdateComponentSettings UpdateComponentSettingEvent;

        public object OwnerActivityNode
        {
            get { return _OwnerActivityNode; }
            set { _OwnerActivityNode = value; }
        }

        public Type WorkflowComponentType
        {
            get { return typeof(HotFolderTrigger); }
        }

        public void LoadSettings(GlobalVariable[] globalVars, WorkflowComponentBase[] fromComponents,
                                 object activityNode, WorkflowComponentBase wfComponent)
        {
            this._OwnerActivityNode = activityNode;
            this._HotFolderTrigger = (HotFolderTrigger) wfComponent;

            this.txt_HotFolderPath.Text = this._HotFolderTrigger.HotFolderPath;
            this.txt_FileNamePattern.Text = this._HotFolderTrigger.FileNamePattern;
            this.ck_IncludeSubFolders.Checked = this._HotFolderTrigger.IncludeSubFolders;

            this.num_Frequency.Value = this._HotFolderTrigger.Interval;
            this.cbo_TimeLapseUnit.SelectedIndex = (int) this._HotFolderTrigger.TimeSpanUnit;
            this.date_Start.Value = this._HotFolderTrigger.StartTime;
            this.time_Start.Value = this._HotFolderTrigger.StartTime;
            if(this._HotFolderTrigger.IsActive)
            {
                this.btn_StartStop.ImageIndex = 3;
                this.lbl_IsActiveStatus.ImageIndex = 1;
            }
            else
            {
                this.btn_StartStop.ImageIndex = 2;
                this.lbl_IsActiveStatus.ImageIndex = 0;
            }
        }

        public void SaveSettings()
        {
            this._HotFolderTrigger.HotFolderPath = this.txt_HotFolderPath.Text;
            this._HotFolderTrigger.HotFolderPath = NetworkShareMap.getUNCPath(this._HotFolderTrigger.HotFolderPath);
            this._HotFolderTrigger.FileNamePattern = this.txt_FileNamePattern.Text.Trim();
            this._HotFolderTrigger.IncludeSubFolders = this.ck_IncludeSubFolders.Checked;

            this._HotFolderTrigger.Interval = (int) this.num_Frequency.Value;
            this._HotFolderTrigger.TimeSpanUnit = (TimeLapseUnit) this.cbo_TimeLapseUnit.SelectedIndex;
            DateTime date = this.date_Start.Value;
            DateTime time = this.time_Start.Value;
            this._HotFolderTrigger.StartTime =
                new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second);
            this._HotFolderTrigger.LastRunTime = this._HotFolderTrigger.StartTime;
            this._HotFolderTrigger.NextRunTime = DateTime.Now;
            switch(this._HotFolderTrigger.TimeSpanUnit)
            {
                case TimeLapseUnit.Second:
                    this._HotFolderTrigger.NextRunTime =
                        this._HotFolderTrigger.LastRunTime.Add(new TimeSpan(0, 0, this._HotFolderTrigger.Interval));
                    break;
                case TimeLapseUnit.Minute:
                    this._HotFolderTrigger.NextRunTime =
                        this._HotFolderTrigger.LastRunTime.Add(new TimeSpan(0, this._HotFolderTrigger.Interval, 0));
                    break;
                case TimeLapseUnit.Hour:
                    this._HotFolderTrigger.NextRunTime =
                        this._HotFolderTrigger.LastRunTime.Add(new TimeSpan(this._HotFolderTrigger.Interval, 0, 0));
                    break;
                case TimeLapseUnit.Day:
                    this._HotFolderTrigger.NextRunTime =
                        this._HotFolderTrigger.LastRunTime.Add(new TimeSpan(this._HotFolderTrigger.Interval, 0, 0, 0));
                    break;
                case TimeLapseUnit.Week:
                    this._HotFolderTrigger.NextRunTime =
                        this._HotFolderTrigger.LastRunTime.Add(new TimeSpan(this._HotFolderTrigger.Interval*7, 0, 0, 0));
                    break;
                case TimeLapseUnit.Month:
                    this._HotFolderTrigger.NextRunTime =
                        this._HotFolderTrigger.LastRunTime.AddMonths(this._HotFolderTrigger.Interval);
                    break;
                case TimeLapseUnit.Year:
                    this._HotFolderTrigger.NextRunTime =
                        this._HotFolderTrigger.LastRunTime.AddYears(this._HotFolderTrigger.Interval);
                    break;
                default:
                    break;
            }
            if(this.lbl_IsActiveStatus.ImageIndex==1)
            {
                this._HotFolderTrigger.IsActive = true;
            }
            else
            {
                this._HotFolderTrigger.IsActive = false;
            }
        }

        /// <summary>
        /// get new files since timestamp specified by last run time of trigger
        /// </summary>
        /// <returns></returns>
        public TestResult Test()
        {
            this.SaveSettings();
            try
            {
                HotFolderOutput[] hotFiles = (HotFolderOutput[])
                                             this._HotFolderTrigger.ProcessTrigger(this._HotFolderTrigger.LastRunTime);
                StringBuilder buffer = new StringBuilder();
                if (hotFiles != null && hotFiles.Length > 0)
                {
                    foreach (HotFolderOutput hotFile in hotFiles)
                    {
                        buffer.Append(Path.GetFileName(hotFile.FilePath) + Environment.NewLine);
                    }
                }
                else
                {
                    buffer.Append("New file changed");
                }
                return new TestResult(true, buffer.ToString());
            }
            catch(Exception ex)
            {
                return new TestResult(false,ex.ToString());
            }
        }

        private void btn_StartStop_Click(object sender, EventArgs e)
        {
            if(this.btn_StartStop.ImageIndex==2)
            {
                // start
                this.btn_StartStop.ImageIndex = 3;
                this.lbl_IsActiveStatus.ImageIndex = 1;
            }
            else
            {
                // stop
                this.btn_StartStop.ImageIndex = 2;
                this.lbl_IsActiveStatus.ImageIndex = 0;
            }
        }

        private void btn_Browse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dlg=new FolderBrowserDialog();
            if(dlg.ShowDialog()==System.Windows.Forms.DialogResult.OK)
            {
                string folderPath = dlg.SelectedPath;
                this.txt_HotFolderPath.Text = NetworkShareMap.getUNCPath(folderPath);
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_OK_Click(object sender, EventArgs e)
        {
            this.SaveSettings();
            if(this.UpdateComponentSettingEvent != null)
            {
                this.UpdateComponentSettingEvent(this._OwnerActivityNode, this._HotFolderTrigger);
            }

            this.Close();
        }

        private void btn_Test_Click(object sender, EventArgs e)
        {
            this.Test();
        }
    }
}
